/**   
 * @Title: TcpServerBuilder.java 
 * @Package com.org.framework.net.tcp.server 
 * @Description: TODO(用一句话描述该文件做什么) 
 * @author cssuger@163.com   
 * @date 2017年10月19日 下午7:44:48 
 * @version V1.0   
 */
package com.bicon.base.data.common.net.tcp.server;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.bicon.base.data.common.net.tcp.TcpServer;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;

/** 
 *@ClassName: TcpServerBuilder 
 *@Description: TODO(这里用一句话描述这个类的作用) 
 *@author cssuger@163.com 
 *@date 2017年10月19日 下午7:44:48  
 */
public abstract class AbstarctServerBuilder implements TcpServer{

	
	private Logger logger = LoggerFactory.getLogger(AbstarctServerBuilder.class);
	
	private  EventLoopGroup boss;
	 
	private EventLoopGroup worker;
	
	private int port = 10027;
	 
	 
	 public AbstarctServerBuilder(){
	    this.boss = new NioEventLoopGroup();
	    this.worker = new NioEventLoopGroup();
	 }
	 
	 public void  init(){
		
		 ServerBootstrap bootstrap = new ServerBootstrap();
		 bootstrap.group(this.boss, this.worker);
		 bootstrap.channel(NioServerSocketChannel.class);
		 bootstrap.childHandler(new ChannelInitializer<SocketChannel>() {

			@Override
			protected void initChannel(SocketChannel ch) throws Exception {
				doHander(ch.pipeline());
				
			}
		});
		 //这是同步的 做法
		 ChannelFuture channelFuture = null;
		 try {
			channelFuture =  bootstrap.bind(port).sync();
			channelFuture.channel().closeFuture().sync();
			
		} catch (InterruptedException e) {
			e.printStackTrace();
		}finally{
			close();
		}
	 }
	 
	 
	 /**
	  * 
	  * @Title: doHander   
	  * @Description: 此处进行抽象，具体实现hander事件链   
	  * @param: @param pipeline      
	  * @return: void      
	  * @throws
	  */
	public abstract void doHander(ChannelPipeline pipeline);
	@Override
	public void doStart() {
		init();
				
		
	}

	@Override
	public void close() {
		boss.shutdownGracefully();
		worker.shutdownGracefully();
		
	}

}
